﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Net.Http.Headers;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ShenNius.Blog.Common
{
    public class WebHelper
    {

        #region 上下页
        public static string UrlParamConcat(params string[] p)
        {
            if (p == null)
            {
                return string.Empty;
            }
            return string.Join("/", p.Where(e => !string.IsNullOrEmpty(e)));
        }

        public static string UrlParamConcatEndWithLine(params string[] p)
        {
            string urls = UrlParamConcat(p);
            return string.IsNullOrEmpty(urls) ? string.Empty : $"{urls}/";
        }

        public static Tuple<string, string> GetUDPager(string format, int pageIndex, int pageSize, int dataCount, string removeStr = "page_1.html")
        {
            int maxPage = GetMaxPage(dataCount, pageSize);
            string prev = pageIndex > 1 ? string.Format(format, pageIndex - 1).TrimEnd(removeStr) : string.Empty;
            string next = pageIndex < maxPage ? string.Format(format, pageIndex + 1) : string.Empty;
            return new Tuple<string, string>(prev, next);
        }

        public static int GetMaxPage(int dataCount, int pageSize)
        {
            return Convert.ToInt32(Math.Ceiling(dataCount * 1.0 / pageSize));
        }
        #endregion


        #region 分页
        public static string ShowPageNavigate(int pageSize, int currentPage, int totalCount, string url)
        {
            pageSize = pageSize == 0 ? 10 : pageSize;
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1);  //总页数
            var output = new StringBuilder();
            if (totalPages > 1)
            {
                if (currentPage != 1)
                {
                    //处理首页连接
                    output.AppendFormat("<a class='pageLink first' href='{0}'>首页</a> ", url);
                }
                if (currentPage > 1)
                {
                    //处理上一页的连接
                    if (currentPage - 1 == 1)
                        output.AppendFormat("<a class='pageLink first' href='{0}'>上一页</a> ", url);
                    else
                        output.AppendFormat("<a class='pageLink prev' href='{0}page_{1}.html'>上一页</a> ", url, currentPage - 1);
                }
                else
                {
                    // output.Append("<span class='pageLink'>上一页</span>");
                }

                output.Append(" ");
                int currint = 1;
                for (int i = 0; i < 5; i++)
                {
                    //一共最多显示10个页码，前面5个，后面5个
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                    {
                        if (currint == i)
                        {
                            //当前页处理
                            output.AppendFormat("<a class='active' href='{0}'>{1}</a> ", url, currentPage);
                        }
                        else
                        {
                            //一般页处理
                            if ((currentPage + i - currint) == 1)
                                output.AppendFormat("<a class='pageLink-num' href='{0}'>{1}</a> ", url, currentPage + i - currint);
                            else
                                output.AppendFormat("<a class='pageLink-num' href='{0}page_{1}.html'>{2}</a> ", url, currentPage + i - currint, currentPage + i - currint);
                        }
                    }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {
                    //处理下一页的链接
                    output.AppendFormat("<a class='pageLink next' href='{0}page_{1}.html'>下一页</a> ", url, currentPage + 1);
                }
                else
                {
                    //output.Append("<span class='pageLink'>下一页</span>");
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    if (totalPages == 1)
                        output.AppendFormat("<a class='pageLink last' href='{0}'>尾页</a> ", url);
                    else
                        output.AppendFormat("<a class='pageLink last' href='{0}page_{1}.html'>尾页</a> ", url, totalPages);
                }
                output.Append(" ");
            }
            output.AppendFormat("  第{0}页 / 共{1}页", currentPage, totalPages);  //这个统计加不加都行
            return output.ToString();
        }
        #endregion
        public static string GetContentFirstImg(string content)
        {
            if (!string.IsNullOrEmpty(content))
            {
                string pat = @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>";
                Regex r = new Regex(pat, RegexOptions.Compiled);
                Match m = r.Match(content);
                if (!m.Success)
                {
                    return "";
                }
                string imgStr = $"{m.Groups[1] + ""}";
                return imgStr;
            }
            else
            {
                return "";
            }
        }
        public static string DealwithContentImg(string content)
        {
            if (!string.IsNullOrEmpty(content))
            {
                string pat = @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>";
                MatchCollection mc = Regex.Matches(content, pat);
                if (mc.Count > 0)
                {
                    for (int i = 0; i < mc.Count; i++)
                    {
                        string str = mc[i].Groups[1].Value;
                        if (!str.Contains("http://imgs.fenfenlg.com"))
                        {
                            content = content.Replace($"{str}", $"http://imgs.fenfenlg.com{str}");
                        }
                    }
                }
                return content;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 301重定向
        /// </summary>
        /// <param name="context"></param>
        public static void RedirectXmlFileRequests(RewriteContext context)
        {
            var url = context.HttpContext.Request.Path.ToString();

            if (url.Contains(".jpg") || url.Contains(".png") || url.Contains(".gif") || url.Contains("favicon.ico"))
            {
                return;
            }
            if (!url.EndsWith("/") && !url.Contains("?") && !url.EndsWith("html"))//不以/结尾需要重定向至 url/ 以html结尾除外 或带问号除外（未配置url映射参数->搜索相关）
            {
                var response = context.HttpContext.Response;
                response.StatusCode = StatusCodes.Status301MovedPermanently;
                context.Result = RuleResult.EndResponse;
                response.Headers[HeaderNames.Location] = $"{url}/";
            }
        }
        public static void WriteLog(string msg)
        {
            Task.Run(() =>
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                var newFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                var logFile = Path.Combine(path, newFileName);
                using (FileStream fs = new FileStream(logFile, FileMode.Append, FileAccess.Write))
                {
                    if (!string.IsNullOrEmpty(msg))
                    {
                        byte[] data = Encoding.Default.GetBytes(msg);
                        fs.Write(data, 0, data.Length);
                    }
                }
            });
        }
    }
}
